package com.bbcare.comm;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

/**
 * 
 * @name:         HuamitechApiUtil.java
 * @author:       tao
 * @createTime:   2017年11月14日
 * @description:  华米api接口授权
 * @modify:
 *
 */
public class HuamitechApiUtil {
    private static Log log = LogFactory.getLog(HuamitechApiUtil.class);

	public final static String TOKEN_URL ="https://auth.huami.com/oauth2/access_token";
	public final static String REFRESH_TOKEN_URL ="https://auth.huami.com/oauth2/refresh_token";
	public final static String AUTHORIZE_PATH ="https://api-open.huami.com";
	public final static String PROFILE_PATH =AUTHORIZE_PATH+"/users/-/profile";
	public final static String ACTIVITIES_PATH =AUTHORIZE_PATH+"/users/-/activities";
	public final static String SLEEP_PATH =AUTHORIZE_PATH+"/users/-/sleep";
	public final static String HEARTRATES_PATH =AUTHORIZE_PATH+"/users/-/heartrates";

	public final static String CLIENT_ID = "client_id";
	public final static String TOKEN_TYPE = "token_type";
	public final static String SCOPE = "scope";
	public final static String STATE = "state";
	public final static String ACCESS_TOKEN = "access_token";
	public final static String EXPIRES_IN = "expires_in";
	public final static String REFRESH_TOKEN = "refresh_token";
	public final static String REDIRECT_URI = "redirect_uri";
	public final static String GRANT_TYPE = "grant_type";
	public final static String CLIENT_SECRET = "client_secret";
	public final static String CODE = "code";
	
	public final static String status_success = "200";
	public final static String status_token_error = "401";
    public static final String INTERVAL_DAY = "daily";
	
	private static final int CONNECT_TIMEOUT = 30 * 1000;
    private static final int SOCKET_TIMEOUT = 30 * 1000;
    private static final int MAX_CON_PER_HOST = 100;
    private static HttpClient httpClient = null;
    
    static{
    	PoolingHttpClientConnectionManager connectionManager =
                new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build());
        // set max connection
        connectionManager.setMaxTotal(MAX_CON_PER_HOST);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .build();

        httpClient = HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }
    
	@SuppressWarnings("finally")
	public static Map<String,String> getHuamiData(String url, List<NameValuePair> params, List<Header> headerList) throws Exception {
    	HttpResponse response = null;
    	Map<String,String> rspMap= new HashMap<String,String>();
    	try {
    		Header[] headerArray = new Header[0];
            if (!CollectionUtils.isEmpty(headerList)) {
                headerArray  = new Header[headerList.size()];
                headerArray = headerList.toArray(headerArray);
            }
            
    		long begin = System.currentTimeMillis();
            URIBuilder builder = new URIBuilder(url);
            if (!CollectionUtils.isEmpty(params)) {
                builder.setParameters(params);
            }
            HttpUriRequest request = new HttpGet(builder.build());
            if (ArrayUtils.isNotEmpty(headerArray)) {
                request.setHeaders(headerArray);
            }
            //华米 获取数据api 请求头
//            request.setHeader("Content-type","application/json");
            log.info("请求华米接口入参："+request.getURI());
            response=httpClient.execute(request);
            log.warn("发送请求,完成,耗时:" + (System.currentTimeMillis() - begin) + "毫秒");
        } catch(Exception ex){  
        	log.error("调用接口error", ex);
        } finally{
        	int statusCode = 0;
            String result =null;
            if(null != response){
            	statusCode = response.getStatusLine().getStatusCode();
            	HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"utf-8");  
                } 
                EntityUtils.consume(response.getEntity()); //会自动释放连接
            }
            rspMap.put("statusCode",statusCode+"");
            rspMap.put("result",result);
            log.info("华米接口返回数据：statusCode:"+statusCode);
//            log.info("华米接口返回数据："+JSON.toJSONString(rspMap));
    	  	return rspMap;
		}
    }
    
    @SuppressWarnings("finally")
	public static Map<String,String> postAuthorization(String url, List<NameValuePair> params,List<Header> headerList) throws Exception {
    	HttpResponse response = null;
    	Map<String,String> rspMap= new HashMap<String,String>();
    	try {
    		Header[] headerArray = new Header[0];
            if (!CollectionUtils.isEmpty(headerList)) {
                headerArray  = new Header[headerList.size()];
                headerArray = headerList.toArray(headerArray);
            }
            
    		long begin = System.currentTimeMillis();
            URIBuilder builder = new URIBuilder(url);
            if (!CollectionUtils.isEmpty(params)) {
                builder.setParameters(params);
            }
            HttpUriRequest request = new HttpPost(builder.build());
            
            //华米 授权固定请求和接收类型  获取token和刷新token
//            request.setHeader("Content-type", "application/x-www-form-urlencoded");
//            request.setHeader("Accept","application/json");
            
            if (ArrayUtils.isNotEmpty(headerArray)) {
                request.setHeaders(headerArray);
            }
            log.info("请求华米接口入参："+request.getURI());
            response = httpClient.execute(request);
            log.warn("发送请求,完成,耗时:" + (System.currentTimeMillis() - begin) + "毫秒");
        }catch(Exception ex){  
            log.error("调用接口error", ex);
        } finally{
	      	 if(response != null) { 
	      		int statusCode = 0;
	            String result =null;
	            if(null != response){
	            	statusCode = response.getStatusLine().getStatusCode();
	            	HttpEntity resEntity = response.getEntity();  
	                if(resEntity != null){  
	                    result = EntityUtils.toString(resEntity,"utf-8");  
	                } 
	                EntityUtils.consume(response.getEntity()); //会自动释放连接
	            }
	            rspMap.put("statusCode",statusCode+"");
	            rspMap.put("result",result);
	            log.info("华米接口返回数据：statusCode:"+statusCode);
			 }
	      	 return rspMap;
        } 
    }
    
    public static void addAuthHeader(List<Header> headerList){
    	headerList.add(new BasicHeader("Accept","application/json"));
    	headerList.add(new BasicHeader("Content-type","application/x-www-form-urlencoded"));
    }
    
    public static void addApiHeader(List<Header> headerList){
    	headerList.add(new BasicHeader("Content-type","application/json"));
    }
    
    //封装授权URL地址
    public static String buildHuamiUrl(Map<String,Object> param){
		String huamiUrl = PropertiesUtils.getProperty("huami_url","http://doctor.bb-care.com/oms/amazfit.html");
		String redirectUrl = PropertiesUtils.getProperty("redirect_uri","https://user.HuaMi.com/oauth/index.html#/?client_id="
				+ "#{client_id}&redirect_uri=#{redirect_uri}&response_type=code&token=access&token=refresh&state=#{state}");
		
		String state ="";
		String userId =  (String)param.get("userId");
//		String tenantId =  (String)param.get("tenantId");
		if(StringUtils.isEmpty(userId)){
			return null;
		}
		state = userId ;
		
		String clientId = PropertiesUtils.getProperty("client_id");
		huamiUrl = huamiUrl.replace("#{redirect_uri}",redirectUrl);
		huamiUrl = huamiUrl.replace("#{client_id}",clientId);
		huamiUrl = huamiUrl.replace("#{state}",state);
		
		return huamiUrl;
	}
    
    //封装授权中转url地址
    public static String buildForwordUrl(Map<String,Object> param){
		String forwordUrl = PropertiesUtils.getProperty("forward_url","");
		String userId =  (String)param.get("userId");
		if(StringUtils.isEmpty(userId)){
			return null;
		}
		forwordUrl = forwordUrl.replace("#{userId}",userId);
		
		return forwordUrl;
	}
    
    public static void main (String [] args ) throws Exception{
    }
}
